﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Exhort.Utility.Entities;
using Exhort.Resolver;
using Exhort.Entity.Basic;
using Exhort.Backstage.Components;

namespace Exhort.Backstage.Areas.Work.Controllers
{
    [Area("Work")]
    public class HomeController : WorkController
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Welcome()
        {
            return View();
        }

        [AllowAnonymous]
        public IActionResult Authorize()
        {
            if (IsAuthenticated)
            {
                return Redirect("/work/home/index");
            }

            return View();
        }

        [AllowAnonymous]
        public async Task<string> Login(string username, string password)
        {
            var result = ServiceResolver.BasicUser.SignIn(username, password);

            if (result.Code == ServiceResultCode.Success)
            {
                var user = result.Data as BasicUser;

                await HttpContext.SignInAsync(CookieScheme, user.ID, username, user.IsSuper);
            }

            return ServiceResult.Serialize(result.Code, result.Message);
        }

        [AllowAnonymous]
        public async Task<IActionResult> Logout()
        {
            if (IsAuthenticated)
            {
                await HttpContext.SignOutAsync(CookieScheme);
            }

            return Redirect("/work/home/authorize");
        }
    }
}